#!/bin/bash

set -e

# === 配置参数 ===
DB_NAME="dmoj"
DB_USER="dmoj"
DB_PASS="your_secure_password"
VENV_NAME="dmojsite"
SITE_DIR="$HOME/$VENV_NAME"
REPO_URL="https://github.com/DMOJ/site.git"
JUDGE_VERSION="v4.0.0"

echo "🌐 配置国内镜像源..."
# apt 镜像（清华源）
sudo sed -i.bak 's|http://.*.ubuntu.com|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list
sudo apt update

echo "📦 安装系统依赖..."
sudo apt install -y git gcc g++ make python3-dev python3-pip libxml2-dev libxslt1-dev zlib1g-dev gettext curl redis-server mariadb-server libmysqlclient-dev supervisor nginx

echo "🛠️ 设置 MariaDB 数据库..."
sudo service mysql start
sudo mariadb -e "CREATE DATABASE IF NOT EXISTS $DB_NAME DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;"
sudo mariadb -e "GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';"
sudo mariadb -e "FLUSH PRIVILEGES;"
sudo mariadb-tzinfo-to-sql /usr/share/zoneinfo | sudo mariadb -u root mysql

echo "🐍 创建 Python 虚拟环境..."
python3 -m venv "$SITE_DIR"
source "$SITE_DIR/bin/activate"

echo "📥 克隆 DMOJ 源码..."
git clone "$REPO_URL" "$SITE_DIR/site"
cd "$SITE_DIR/site"
git checkout "$JUDGE_VERSION"
git submodule init
git submodule update

echo "📦 安装 Python 依赖..."
# pip 镜像（清华 PyPI）
mkdir -p ~/.pip
cat > ~/.pip/pip.conf <<EOF
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
timeout = 600
EOF
pip3 install -r requirements.txt
pip3 install mysqlclient uwsgi websocket-client

echo "⚙️ 配置 local_settings.py..."
cp dmoj/local_settings.py.example dmoj/local_settings.py
sed -i "s/'USER': 'dmoj'/'USER': '$DB_USER'/g" dmoj/local_settings.py
sed -i "s/'PASSWORD': 'password'/'PASSWORD': '$DB_PASS'/g" dmoj/local_settings.py

echo "✅ 检查 Django 配置..."
python3 manage.py check

echo "🎨 编译前端资源..."
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
# npm 镜像（淘宝源）
npm config set registry https://registry.npmmirror.com
npm install -g sass postcss-cli postcss autoprefixer
./make_style.sh
python3 manage.py collectstatic --noinput
python3 manage.py compilemessages
python3 manage.py compilejsi18n

echo "🧱 初始化数据库..."
python3 manage.py migrate
python3 manage.py loaddata navbar language_small demo
python3 manage.py createsuperuser

echo "🚦 启动 Redis..."
sudo service redis-server start

echo "🧪 测试运行服务..."
python3 manage.py runserver 0.0.0.0:8000 &
sleep 10
pkill -f runserver

python3 manage.py runbridged &
sleep 10
pkill -f runbridged

celery -A dmoj_celery worker &
sleep 10
pkill -f "celery"

echo "🧩 配置 uWSGI..."
cat > uwsgi.ini <<EOF
[uwsgi]
chdir = $SITE_DIR/site
module = dmoj.wsgi:application
home = $SITE_DIR
master = true
processes = 4
socket = 127.0.0.1:8001
vacuum = true
EOF

uwsgi --ini uwsgi.ini &
sleep 5
pkill -f uwsgi

echo "🧩 配置 supervisord..."
sudo cp ../docs/sample_files/site.conf /etc/supervisor/conf.d/
sudo cp ../docs/sample_files/bridged.conf /etc/supervisor/conf.d/
sudo cp ../docs/sample_files/celery.conf /etc/supervisor/conf.d/
sudo supervisorctl update
sudo supervisorctl status

echo "🌐 配置 nginx..."
sudo cp ../docs/sample_files/nginx.conf /etc/nginx/conf.d/dmoj.conf
sudo nginx -t && sudo service nginx reload

echo "📡 配置事件服务器..."
mkdir -p websocket
cat > websocket/config.js <<EOF
module.exports = {
  get_host: '127.0.0.1',
  get_port: 15100,
  post_host: '127.0.0.1',
  post_port: 15101,
  http_host: '127.0.0.1',
  http_port: 15102,
  long_poll_timeout: 29000,
};
EOF

npm install qu ws simplesets
sudo cp ../docs/sample_files/wsevent.conf /etc/supervisor/conf.d/
sudo supervisorctl update
sudo supervisorctl restart bridged
sudo supervisorctl restart site
sudo service nginx restart

echo "✅ 安装完成！请访问你的服务器地址进行验证。"
